import { expect } from '@jest/globals';
import { JsonReader } from '@ohos/hvigor/src/base/util/json-reader';
import fse from 'fs-extra';
import path from 'path';

import { initExecuteCommand, runHvigorFailAsync } from '../../../../common/common';
import { buildServiceCard } from '../../../../plugins/common-fun';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType
} from '../../../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../../../plugins/task-builder/test-case';
import { TestTaskOptionBuilder } from '../../../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API10,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility
  }
};

const testFun: TestCaseFun = async (project, taskConfig, record) => {
  const projectRootPath = project.projectRootPath();
  const command = initExecuteCommand({
    mode: 'module',
    product: 'default',
    tasks: 'assembleHap'
  });
  const moduleRootPath = project.getModule('entry').moduleRootPath();
  await buildServiceCard(moduleRootPath, 'HelloWorld', 'Image', 'Immersive');
  const formConfigPath = path.resolve(moduleRootPath, 'src/main/resources/base/profile/form_config.json');
  const forms = await JsonReader.getJsonObj(formConfigPath, 'utf-8');
  for (const key in forms.forms) {
    if (Object.prototype.hasOwnProperty.call(forms.forms, key)) {
      forms.forms[key].isDefault = true;
    }
  }

  await fse.writeFile(formConfigPath, JSON.stringify(forms, null, 2), 'utf-8');
  const result = await runHvigorFailAsync(projectRootPath, command);
  record.addStep('所有卡片的isDefault属性为true时', result);
  expect(result.stderr).toContain('Failed :entry:default@MakePackInfo');
  expect(result.stderr).toContain('Only one default card can be configured');
  expect(result.stderr).toContain(`${formConfigPath}`);
};

TestCaseBuilder.builder()
  .caseName('validateFormsIsDefault')
  .description('form_config.json中只有一个form的isDefault为true')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(TestTaskOptionBuilder.builder().caseLevel(CaseLevel.L2).build())
  .testFun(testFun)
  .load();
